const express = require('express');
const router = express.Router();
const packageService = require('../services/PackageService');

// 获取包列表
router.get('/', async (req, res) => {
  try {
    const { page = 1, pageSize = 20, query = '', tagId = '', sortBy = 'downloads', sortOrder = 'desc' } = req.query;
    const result = await packageService.getPackages({
      page: parseInt(page),
      limit: parseInt(pageSize),
      sortBy,
      sortOrder,
      keyword: query,
      tagId
    });
    
    // 格式化返回数据以匹配前端期望
    res.json({
      items: result.packages,
      total: result.total,
      pages: result.pages,
      currentPage: result.currentPage
    });
  } catch (error) {
    console.error('获取包列表失败:', error);
    // 即使出错也返回正确的格式
    res.status(500).json({
      items: [],
      total: 0,
      pages: 0,
      currentPage: 1,
      error: error.message || '获取包列表失败'
    });
  }
});

// 创建包
router.post('/', async (req, res) => {
  try {
    const packageData = req.body;
    const result = await packageService.createPackage(packageData);
    res.status(201).json(result);
  } catch (error) {
    console.error('创建包失败:', error);
    res.status(500).json({ error: error.message || '创建包失败' });
  }
});

// 更新包
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const packageData = req.body;
    const result = await packageService.updatePackage(id, packageData);
    res.json(result);
  } catch (error) {
    console.error('更新包失败:', error);
    res.status(500).json({ error: error.message || '更新包失败' });
  }
});

// 删除包
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    await packageService.deletePackage(id);
    res.json({ success: true, message: '删除成功' });
  } catch (error) {
    console.error('删除包失败:', error);
    res.status(500).json({ error: error.message || '删除包失败' });
  }
});

// 获取包详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const packageInfo = await packageService.getPackageDetailById(id);
    res.json(packageInfo);
  } catch (error) {
    console.error('获取包详情失败:', error);
    if (error.message === '包不存在') {
      res.status(404).json({ error: '包不存在' });
    } else {
      res.status(500).json({ error: error.message || '获取包详情失败' });
    }
  }
});

// 搜索包
router.get('/search', async (req, res) => {
  try {
    const { q, limit = 10 } = req.query;
    const packages = await packageService.searchPackages(q, limit);
    res.json(packages);
  } catch (error) {
    console.error('搜索包失败:', error);
    res.status(500).json({ error: error.message || '搜索包失败' });
  }
});

// 获取热门包
router.get('/trending/popular', async (req, res) => {
  try {
    const packages = await packageService.getPopularPackages();
    res.json(packages);
  } catch (error) {
    console.error('获取热门包失败:', error);
    res.status(500).json({ error: error.message || '获取热门包失败' });
  }
});

module.exports = router;